<template>
  <view class="goods-detail">
    <!-- 顶部导航栏-->
    <HeaderNav title="商品详细"></HeaderNav>

    <!-- 封面图-->
    <view class="goods-cover">
      <image :src="goodDetail['large_img']">
      </image>
    </view>

    <!-- 信息卡片-->
    <view class="goods-card">
      <view class="goods-info">
        <view class="card-header">
          <view class="header-l">
            <view class="coffee-name">
              {{goodDetail['name']}}
            </view>
            <view class="coffee-name-en">
              {{goodDetail['enname']}}
            </view>
          </view>
          <view class="header-r">
            ￥{{goodDetail['price']}}
          </view>
        </view>

        <view class="taste" v-for="(type,index) in goodDetail['typeArr']" :key="index">
          <view class="taste-title">
            {{type['type']}}
          </view>
          <view @click="changeIdxHandler(index,count)" class="taste-item" :class="type['typeIdx']===count?'active':''"
            v-for="(val,count) in type['typeVal']" :key="count">
            {{val}}
          </view>
        </view>
        <view class="goods-num">
          <view class="num-title">
            选择数量
          </view>
          <view class="num-opera">
            <view class="dec" @click="decHandler">
              <image src="../../static/svg/dec.svg"></image>
            </view>
            <view class="num">
              {{count}}
            </view>
            <view class="inc" @click="incHandler">
              <image src="../../static/svg/inc.svg"></image>
            </view>
          </view>
        </view>
        <view class="goods-desc">
          <view class="desc-title">
            商品描述
          </view>
          <view class="desc-content">
            <view class="desc-row" v-for="(desc,index) in goodDetail['desc']" :key="index">{{index+1}}
              、
              {{desc}}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view class="goods-carts">
      <view class="carts-l">
        <view class="l">
          <view class="badge" v-show="badge">
            {{badge>9?'...':badge}}
          </view>
          <view class="icon" @click="goShopBagHandler">
            <image src="../../static/svg/bag.svg" v-show="!badge"></image>
            <image src="../../static/svg/bag_a.svg" v-show="badge"></image>
          </view>
          <view class="text">
            购物袋
          </view>
        </view>
        <view class="l">
          <view class="icon">
            <image @click="collectHandler(goodDetail['pid'])" v-show="allPid.indexOf(goodDetail['pid'])===-1"
              src="../../static/svg/collect.svg">
            </image>
            <image @click="notCollectHandler(goodDetail['pid'])" v-show="allPid.indexOf(goodDetail['pid'])!==-1"
              src="../../static/svg/collect_a.svg"></image>
          </view>
          <view class="text">
            {{allPid.indexOf(goodDetail['pid'])!==-1?'已收藏':'未收藏'}}
          </view>
        </view>
      </view>
      <view class="carts-r">
        <view class="add-carts" @click="addShopcartHandler">
          加入购物袋
        </view>
        <view class="pay-goods" @click="payHandler">
          立即购买
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    uniToast
  } from '../utils/uni/uni.js'
  import HeaderNav from "../../components/HeaderNav/HeaderNav.vue"
  import {
    req
  } from "../utils/request/request.js"
  import {
    mapGetters
  } from 'vuex'
  export default {
    components: {
      HeaderNav
    },
    computed: {
      ...mapGetters('user', ['isLogin']),
      /* 计算当前商品是否在购物车中 */
      badge() {
        const curPid = this.goodDetail['pid']
        const find = this.baseCartShop.find(x => x['pid'] === curPid)
        if (find) {
          return find['count']
        }
        return 0
      }
    },
    data() {
      return {
        count: 1,
        /* 当前商品的信息对象 */
        goodDetail: {},
        /* 记录已收藏的商品id */
        allPid: [],
        baseCartShop: []
      };
    },
    onLoad(opt) {
      this.getGoodDetail(opt['wd'])
      this.isLogin && this.findAllLike()
    },
    onShow() {
      this.getBaseCartShop()
    },
    methods: {

      /* 获取购物车的商品 */
      getBaseCartShop() {
        if (!this.isLogin) return;
        req('findAllShopcart', {
          isToken: true
        }).then(({
          data: res
        }) => {
          this.baseCartShop = res['result']
        }, err => {
          console.log(err);
        })
      },
      /* 立即购买*/
      payHandler() {
        if (!this.isLogin) {
          this.showModel()
          return;
        };
        this.addShopcartHandler((res) => {
          uni.navigateTo({
            url: "/pages/order/order?sids=" + JSON.stringify([res['sid']])
          })
        }, true)
      },
      /* 前往商品购物车*/
      goShopBagHandler() {
        if (!this.isLogin) {
          this.showModel()
          return
        }
        uni.switchTab({
          url: '/pages/shopbag/shopbag'
        })
      },
      /* 获取所有收藏商品 */
      findAllLike() {
        req('findAllLike', {
          isToken: true
        }).then(({
          data: res
        }) => {
          res.result.forEach(x => {
            this.allPid.push(x['pid'])
          })
        })
      },

      /* 添加商品至购物袋 */
      addShopcartHandler(w, f) {
        if (!this.isLogin) {
          this.showModel()
          return;
        }
        const rules = this['goodDetail']['typeArr']
        let rule = []
        rules.map(e => {
          rule.push(e['typeVal'][e['typeIdx']]);
        })
        rule = rule.join('/')
        const {
          pid,

        } = this.goodDetail
        const collectData = {
          pid,
          count: this.count,
          rule
        }

        req('addShopcart', {
          reqData: collectData,
          method: 'POST',
          isToken: true
        }).then(({
            data: res
          }) => {
            if (res['code'] === 3000) {
              if (f) {
                w && w(res)
                return
              } else {
                uniToast(res['msg'])
                this.getBaseCartShop()
              }
            }
          },
          err => {
            console.log(err);
          })
      },
      /* 取消收藏*/
      notCollectHandler(pid) {
        if (!this.isLogin) {
          this.showModel()
          return;
        };
        req('notlike', {
          reqData: {
            pid
          },
          method: 'post',
          isToken: true
        }).then(({
          data: res
        }) => {
          if (res.code === 900) {
            const index = this.allPid.indexOf(pid)
            this.allPid.splice(index, 1)
            return uniToast("取消收藏", 'success')
          }
          uniToast(res.msg, 'error')
        }, err => {
          console.log(err);
        })
      },
      /* 收藏*/
      collectHandler(pid) {
        if (!this.isLogin) {
          this.showModel()
          return
        };
        req('like', {
          reqData: {
            pid
          },
          isToken: true,
          method: 'post'
        }).then(({
          data: res
        }) => {
          if (res.code === 800) {
            this.allPid.push(pid)
            return uniToast("收藏成功", 'success')
          }
          uniToast(res.msg, 'error')
        }, err => {
          console.log(err);
        })
      },
      /* 变换口味*/
      changeIdxHandler(index, count) {
        this.$set(this.goodDetail['typeArr'][index], 'typeIdx', count)
      },
      /* 加*/
      incHandler() {
        this.count < 999 ? this.count++ : false
      },
      /* 减*/
      decHandler() {
        this.count > 1 ? this.count-- : false
      },
      /* 获取商品详细*/
      async getGoodDetail(pid) {
        const {
          data: {
            result
          }
        } = await req("productDetail", {
          reqData: {
            pid
          }
        })
        const data = result[0]
        const type = ["cream", "milk", "tem", "sugar"]
        const typeRes = []
        type.map(item => {
          let obj = {}
          obj.typeIdx = 0
          obj.type = data[item + '_desc']
          obj.typeVal = data[item].split('/')
          if (obj.typeVal[0] != "") {
            typeRes.push(obj)
          }
        })
        data['typeArr'] = typeRes
        data['desc'] = data['desc'].split(/\n/)
        this.goodDetail = data;
      },
      /* 返回上一级*/
      comeBack() {
        uni.navigateBack()
      },
      /* 显示拟态框 */
      showModel() {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            res.confirm && uni.navigateTo({
              url: '/pages/login/login'
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  .goods-detail {
    padding-bottom: 80rpx;
    background-color: #f7f7f7;


    .goods-card {
      padding: 0 30rpx;
      transform: translateY(-50rpx);

      .goods-info {
        background-color: #fff;
        border-radius: 15rpx;
        padding: 50rpx 40rpx;

        .taste {
          margin-top: 40rpx;
          white-space: nowrap;
          display: flex;
          align-items: center;

          .taste-title {
            color: #666768;
            font-size: 26rpx;
            // margin-right: 100rpx;
            width: 120rpx;
          }

          .taste-item {
            background-color: #e8e8e8;
            justify-content: center;
            margin-right: 40rpx;
            border-radius: 50rpx;
            padding: 10rpx 0;
            font-size: 30rpx;
            font-size: 24rpx;
            width: 136rpx;
            display: flex;
            align-items: center;

            &:last-child {
              margin-right: 0;
            }

            &.active {
              color: #fff;
              background-color: #0c34ba;
            }
          }
        }

        .goods-num {
          display: flex;
          justify-content: space-between;
          margin-top: 50rpx;
          padding-top: 30rpx;
          padding-bottom: 30rpx;
          border-top: 1px solid #e8e8e8;
          border-bottom: 1px solid #e8e8e8;

          .num-title {
            color: #646566;
            font-size: 26rpx;
          }

          .num-opera {
            display: flex;
            align-items: center;

            .num {
              margin: 0 20rpx;
              width: 50rpx;
              display: flex;
              justify-content: center;
              align-items: center;
            }

            .inc,
            .dec {
              height: 50rpx;
              width: 50rpx;
              overflow: hidden;

              image {
                width: 100%;
                height: 100%;
              }
            }

            .dec {
              height: 40rpx;
              width: 40rpx;
            }
          }

        }

        .goods-desc {
          margin-top: 40rpx;

          .desc-title {
            font-size: 26rpx;
          }

          .desc-content {
            margin-top: 40rpx;



            .desc-row {
              margin-bottom: 20rpx;
              font-size: 24rpx
            }
          }
        }

        .card-header {

          display: flex;
          justify-content: space-between;
          align-items: center;

          .header-l {
            display: flex;
            flex-direction: column;
            color: #767e86;
            flex: 3;

            .coffee-name {
              font-weight: bold;
              font-size: 40rpx;
              width: 250rpx;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }

            .coffee-name-en {
              font-size: 20rpx;
              width: 250rpx;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }

          .header-r {
            flex: 1;
            color: #0c34ba;
            font-weight: bold;
            font-size: 35rpx
          }
        }
      }
    }

    .goods-cover {
      image {
        width: 100%;
      }
    }

    .goods-carts {
      display: flex;
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 90rpx;
      background-color: #fff;
      align-items: center;
      justify-content: space-between;
      padding: 0 38rpx;
      box-shadow: 2rpx 0 50rpx 10rpx #3333331c;

      .carts-l {
        display: flex;

        .l {
          display: flex;
          flex-direction: column;
          align-items: center;
          position: relative;

          &:first-child {
            margin-right: 40rpx;

            .badge {
              position: absolute;
              background-color: #0c34ba;
              width: 30rpx;
              height: 30rpx;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: 600;
              color: #fff;
              top: -12rpx;
              right: 0;
              font-size: 10rpx;
              z-index: 10;
            }
          }

          .text {
            font-size: 20rpx;
            color: #333;
          }

          .icon {
            height: 35rpx;
            width: 35rpx;

            image {
              height: 100%;
              width: 100%;
            }
          }
        }
      }

      .carts-r {
        display: flex;

        .pay-goods,
        .add-carts {
          background-color: #0c34ba;
          color: #fff;
          font-size: 24rpx;
          height: 70rpx;
          display: flex;
          align-items: center;
          padding: 0 60rpx;
        }

        .pay-goods {
          border-top-right-radius: 50rpx;
          border-bottom-right-radius: 50rpx;
        }

        .add-carts {
          border-top-left-radius: 50rpx;
          border-bottom-left-radius: 50rpx;
          background-color: #6a91ec;
        }
      }
    }
  }
</style>
